﻿Imports System.Data.OleDb
Public Class addacake
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If User.Identity.IsAuthenticated Then
            'Excellent no problem
        Else
            'Redirect to home
            Response.Redirect("opps.aspx?id=4")
        End If
    End Sub

    Protected Sub btn_submitCake_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submitCake.Click

        Dim newFileName As String
        newFileName = Guid.NewGuid().ToString() & getSuffix(fu_CakePic.FileName)
        fu_CakePic.SaveAs(Server.MapPath("Pictures") & "/" & newFileName)

        Dim usernumber As Integer
        usernumber = Class1.getUserNumber(User.Identity.Name)

        Dim cakenumber As Integer

        Dim sql As String = "INSERT INTO Cakes (CakeTitle,Author,CakeDescription,CakeRating,CakePictureMain) VALUES (@f1,@f2,@f3,@f4,@f5)"
        Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("CakeConnection").ConnectionString)
        Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)
        cmd.Parameters.AddWithValue("@f1", tb_Title.Text)
        cmd.Parameters.AddWithValue("@f2", usernumber)
        cmd.Parameters.AddWithValue("@f3", tb_CakeDesc.Text)
        cmd.Parameters.AddWithValue("@f4", 2)
        cmd.Parameters.AddWithValue("@f5", "Pictures/" & newFileName)
        conn.Open()
        cmd.ExecuteNonQuery()
        conn.Close()
        cmd.Dispose()
        conn.Dispose()

        'Get the cakeNumber (Not the best way but Access prevents using Scope_identiy as far as I can tell)
        Dim sql2 As String = "SELECT MAX(ID) FROM Cakes"

        Dim conn2 As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("CakeConnection").ConnectionString)
        Dim cmd2 As OleDbCommand = New OleDbCommand(sql2, conn2)

        conn2.Open()

        cakenumber = cmd2.ExecuteScalar()

        conn2.Close()
        cmd2.Dispose()
        conn2.Dispose()
        Class1.addCakePoint(usernumber, 10, "AddCake")
        Response.Redirect("addacake2.aspx?cakeId=" & cakenumber)

    End Sub

    Function getSuffix(ByVal fn As String)
        Dim fileParts = fn.Split(".")
        Dim suffix = fileParts(fileParts.Length - 1)
        Return "." & suffix
    End Function

End Class